﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Hangjing.Common;
using Hangjing.SQLServerDAL;
using Hangjing.Model;
using Hangjing.DBUtility;
using System.IO;
using MVCNPOIHelper.Common;

/// <summary>
///代客下单统计
/// </summary>
public partial class qy_54tss_Admin_Sale_valetorder : System.Web.UI.Page
{
    /// <summary>
    /// 管理员条件
    /// </summary>
    private string SqlWhere
    {
        get
        {
            object o = ViewState["SqlWhere"];
            return (o == null) ? "" : Convert.ToString(o);
        }
        set
        {
            ViewState["SqlWhere"] = value;
        }
    }

    /// <summary>
    /// 订单条件
    /// </summary>
    private string orderWhere
    {
        get
        {
            object o = ViewState["orderWhere"];
            return (o == null) ? "" : Convert.ToString(o);
        }
        set
        {
            ViewState["orderWhere"] = value;
        }
    }

    /// <summary>
    /// 排序字段
    /// </summary>
    protected string ordersort
    {
        get
        {
            object o = ViewState["ordersort"];
            return (o == null) ? "ordercount" : Convert.ToString(o);
        }
        set
        {
            ViewState["ordersort"] = value;
        }
    }

    Deliver bll = new Deliver();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            SqlWhere = " 1=1 ";
            SqlWhere = new RightsTool().getDeliverWhere(SqlWhere);
            orderWhere = "  1=1 and delflag = 0  ";
            orderWhere = new RightsTool().getOrderWhere(orderWhere);

            WebUtility.SetDDLCity(ddlcity);
            WebUtility.SetDDLGroup(ddlGpsIMEI);

            new OrderState().BindOrderState(rblstate);

            int gid = HjNetHelper.GetQueryInt("gid", 0);
            if (gid > 0)
            {
                tbStartTime.Text = DateTime.Now.ToShortDateString();
                this.tbEndTime.Text = DateTime.Now.ToShortDateString();

                WebUtility.SelectValue(ddlGpsIMEI, gid);
            }

            ddldelflag.Items[1].Selected = true;

            InitSqlwhere();
            if (gid > 0)
            {
                BindData();
            }
        }
    }

    /// <summary>
    /// 绑定指定的数据
    /// </summary>
    protected void BindData()
    {

        DateTime start1 = Convert.ToDateTime(tbStartTime.Text);
        DateTime end1 = Convert.ToDateTime(tbEndTime.Text);
        int xAxisCount = Convert.ToInt32((end1 - start1).TotalDays) + 1;


        string otherwhere = " 1=1 ";
        string paramskey = ddlparams.SelectedValue;
        if (paramskey != "-1")
        {
            decimal value = 0;
            try
            {
                value = Convert.ToDecimal(tbfirst.Text);
            }
            catch (Exception)
            {
                AlertScript.AjaxRegisterScript("alert('条件参数错误，请输入数字','text:操作失败!','250','150','true','2000','true','text');", Page);
                return;
            }


            switch (paramskey)
            {
                case "orderusetime":
                case "sendtime":
                    value = value * 60;
                    break;
            }

            otherwhere += " and " + paramskey + " " + ddlop.SelectedValue + " " + value + "";

        }


        IList<DeliverGroupInfo> groups = SectionProxyData.GetEdelivergroupList();

        IList<TogoInfo> shops = bll.SendOrderStatistics(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, SqlWhere, orderWhere, ordersort, xAxisCount, otherwhere);
        if (shops.Count > 0)
        {
            this.AspNetPager1.RecordCount = shops[0].DataID;
        }
        if (xAxisCount > 0)
        {
            foreach (var item in shops)
            {
                item.Introduce = "/Admin/shop/OrderList.aspx?did=" + item.IsDelete + "&start=" + tbStartTime.Text + "&end=" + tbEndTime.Text;
                item.EBuilding = (item.ShopHaveMoney / xAxisCount).ToString("0.0");
                item.Tel = (item.allcount * 1.0M / xAxisCount).ToString("0.0");

                foreach (var group in groups)
                {
                    if (group.ID.ToString() == item.Fetion)
                    {
                        item.Fetion = group.classname;
                        break;
                    }
                }

            }
        }



        string sql = orderWhere;

        sql += " and EXISTS(SELECT dataid FROM dbo.Deliver WHERE dataid = Custorder.deliverid AND " + SqlWhere + " )";


        CustorderInfo count = new Custorder().GetSumSendTime(sql);

        lbordercount.InnerText = count.OrderCount.ToString();
        lballprice.InnerText = count.shopdiscountmoney.ToString();
        lbperorder.InnerText = (count.OrderCount * 1.0M / xAxisCount).ToString("0.0");
        lbpersendfee.InnerText = (count.shopdiscountmoney * 1.0M / xAxisCount).ToString("0.0");
        lbpersendtime.InnerText = Utils.second2MinAndSecond((count.delflag));
        lbperordertime.InnerText = Utils.second2MinAndSecond((count.UserId));
        timeoutcount.InnerText = count.deliversiteid.ToString();
        lbadvance.InnerText = count.Advance.ToString();
        lbCommission.InnerText = count.Commission.ToString();


        lbdelivergetfee_base.InnerText = count.delivergetfee_base.ToString();
        lbDeliverGetSendFee.InnerText = count.DeliverGetSendFee.ToString();


        timeoutrat.InnerText = "";
        if (count.OrderCount > 0)
        {
            timeoutrat.InnerText = (count.deliversiteid * 1.0 / count.OrderCount * 100).ToString("0.0") + "%";
        }
        lbcardpay.InnerText = count.cardpay.ToString();

        this.rptsum.DataSource = shops;
        this.rptsum.DataBind();

        AlertScript.AjaxRegisterScript("init();;", Page);


    }

    protected void btSearch_Click(object sender, EventArgs e)
    {
        InitSqlwhere();
        BindData();
    }

    /// <summary>
    /// 时间变化搜索
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void settime_Click(object sender, EventArgs e)
    {
        DateTime dt = DateTime.Now; //当前时间
        string starttime = this.tbStartTime.Text;
        string endtime = this.tbEndTime.Text;
        Button bt = (Button)sender;
        switch (bt.ID)
        {
            case "btpre"://前一天
                if (starttime != "")
                {
                    tbStartTime.Text = Convert.ToDateTime(starttime).AddDays(-1).ToShortDateString() + "";
                }
                else
                {
                    return;
                }
                if (endtime != "")
                {
                    tbEndTime.Text = Convert.ToDateTime(endtime).AddDays(-1).ToShortDateString() + "";
                }
                else
                {
                    return;
                }
                break;
            case "btyestoday"://昨天
                tbStartTime.Text = DateTime.Now.AddDays(-1).ToShortDateString() + "";
                tbEndTime.Text = DateTime.Now.AddDays(-1).ToShortDateString() + "";

                break;
            case "tbtoday"://今天
                tbStartTime.Text = DateTime.Now.ToShortDateString() + "";
                tbEndTime.Text = DateTime.Now.ToShortDateString() + "";

                break;
            case "btnext"://后一天
                if (starttime != "")
                {
                    tbStartTime.Text = Convert.ToDateTime(starttime).AddDays(1).ToShortDateString() + "";
                }
                else
                {
                    return;
                }
                if (endtime != "")
                {
                    tbEndTime.Text = Convert.ToDateTime(endtime).AddDays(1).ToShortDateString() + "";
                }
                else
                {
                    return;
                }
                break;
            case "tbweek"://本周

                DateTime startWeek = dt.AddDays(1 - Convert.ToInt32(dt.DayOfWeek.ToString("d")));
                tbStartTime.Text = startWeek.ToDate();

                tbEndTime.Text = DateTime.Now.ToShortDateString() + "";
                break;
            case "tbmonth"://本月
                tbStartTime.Text = DateTime.Now.ToString("yyyy-MM-01") + "";
                tbEndTime.Text = DateTime.Now.ToShortDateString() + "";
                break;
            case "tbyear"://本年
                tbStartTime.Text = DateTime.Now.ToString("yyyy-01-01") + "";
                tbEndTime.Text = DateTime.Now.ToShortDateString() + "";

                break;
            default:
                break;
        }
        InitSqlwhere();

        BindData();
    }


    /// <summary>
    /// 生成查询条件
    /// </summary>
    protected void InitSqlwhere()
    {
        SqlWhere = " 1=1  ";
        SqlWhere = new RightsTool().getDeliverWhere(SqlWhere);
        orderWhere = " 1=1 and delflag = 0 ";
        orderWhere = new RightsTool().getOrderWhere(orderWhere);
        if (this.tbStartTime.Text != "")
        {
            orderWhere += " and  [OrderDateTime] > '" + WebUtility.InputText(this.tbStartTime.Text) + "' ";
        }
        if (this.tbEndTime.Text != "")
        {
            orderWhere += " and OrderDateTime < '" + WebUtility.InputText(this.tbEndTime.Text) + " 23:59:59'";
        }
        string ids = WebUtility.GetcheckStr(rblstate);
        if (ids != "")
        {
            orderWhere += " and OrderStatus  in (" + ids + ")";
        }
        if (tbshopname.Text != "")
        {
            orderWhere += " and EXISTS (SELECT Unid FROM dbo.Points WHERE Unid = dbo.Custorder.togoid  ";
            orderWhere += " and Name like '%" + Utils.RegEsc(WebUtility.InputText(this.tbshopname.Text.Trim())) + "%' )";
        }

        if (ddlcity.SelectedValue != "0")
        {
            SqlWhere += " and Inve1 = " + ddlcity.SelectedValue + "";
        }
        if (ddlGpsIMEI.SelectedValue != "-1")
        {
            SqlWhere += " and GpsIMEI = " + ddlGpsIMEI.SelectedValue + "";
        }
        if (ddldelflag.SelectedValue != "-1")
        {
            SqlWhere += " and delflag = " + ddldelflag.SelectedValue + "";
        }


        if (cbremoveele.Checked == true)
        {
            orderWhere += " and EXISTS (SELECT Unid FROM dbo.Points WHERE Unid = dbo.Custorder.togoid  ";
            orderWhere += " and Name not like '饿了么-%' )";
        }



        if (cbremoveexcel.Checked == true)
        {
            orderWhere += " and fromweb <> '" + (int)OrderSource.ExcelImport + "'";
        }

        if (tbdelivername.Text != "")
        {
            SqlWhere += " and Name like '%" + Utils.RegEsc(WebUtility.InputText(this.tbdelivername.Text.Trim())) + "%' ";
        }
        if (ddreveint1.SelectedValue != "-1")
        {
            SqlWhere += " and reveint1 = " + ddreveint1.SelectedValue + "";
        }
        if (ddlpost.SelectedValue != "-1")
        {
            SqlWhere += " and post = '" + ddlpost.SelectedValue + "'";
        }
        if (ddlgrade.SelectedValue != "-1")
        {
            SqlWhere += " and grade = " + ddlgrade.SelectedValue + "";
        }
        if (ddlcarower.SelectedValue != "-1")
        {
            SqlWhere += " and carower = " + ddlcarower.SelectedValue + "";
        }
        if (tbcartype.SelectedValue != "-1")
        {
            SqlWhere += " and cartype = '" + tbcartype.SelectedValue + "'";
        }




        //Response.Write(orderWhere);
    }


    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        BindData();
    }


    protected void btExport_Click(object sender, EventArgs e)
    {
        //WebUtility.FixsetCookie("webStatisticsExcleOrder", Server.UrlEncode(SqlWhere), 1);
        //Response.Redirect("DeliverordersumToExcel.aspx");

        //判断权限
        int _rs = WebUtility.checkOperator_super(7);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page,  "alert('无操作权限','success','true',5);init();");
            return;
        }

        var models = new List<TogoInfo>();

        DateTime start1 = Convert.ToDateTime(tbStartTime.Text);
        DateTime end1 = Convert.ToDateTime(tbEndTime.Text);
        int xAxisCount = Convert.ToInt32((end1 - start1).TotalDays) + 1;

        string otherwhere = " 1=1 ";
        string paramskey = ddlparams.SelectedValue;
        if (paramskey != "-1")
        {
            decimal value = 0;
            try
            {
                value = Convert.ToDecimal(tbfirst.Text);
            }
            catch (Exception)
            {
                AlertScript.AjaxRegisterScript("alert('条件参数错误，请输入数字','text:操作失败!','250','150','true','2000','true','text');", Page);
                return;
            }


            switch (paramskey)
            {
                case "orderusetime":
                case "sendtime":
                    value = value * 60;
                    break;
            }

            otherwhere += " and " + paramskey + " " + ddlop.SelectedValue + " " + value + "";

        }


        IList<TogoInfo> shops = bll.SendOrderStatistics(1000, 1, SqlWhere, orderWhere, "ordercount", xAxisCount, otherwhere);
        IList<DeliverGroupInfo> groups = SectionProxyData.GetEdelivergroupList();


        if (xAxisCount > 0)
        {
            foreach (var item in shops)
            {
                item.Introduce = "/Admin/shop/OrderList.aspx?did=" + item.IsDelete + "&start=" + tbStartTime.Text + "&end=" + tbEndTime.Text;
                item.EBuilding = (item.ShopHaveMoney / xAxisCount).ToString("0.0");
                item.Tel = (item.allcount * 1.0M / xAxisCount).ToString("0.0");

                foreach (var group in groups)
                {
                    if (group.ID.ToString() == item.Fetion)
                    {
                        item.Fetion = group.classname;
                        break;
                    }
                }
                item.Remark = Hangjing.WebCommon.WebHelper.TurnPost(item.Grade);

            }
        }


        models.AddRange(shops);

        Stream stream = null;

        string dirurl = Hangjing.WebCommon.WebHelper.CreateDirectoryByMonth(Context);
        string filepath = dirurl + DateTime.Now.ToString("yyyyMMddHHmm") + ".xls";

        var excelColumns = ExcelColumns.Create(Server.MapPath("~/App_Data/DeliverOrderSumImport.xml"), "root/export/row");
        if (models.Count < 36000)
        {
            stream = NpoiExcelHelper.RenderToExcelIList(models, excelColumns, NpoiExcelHelper.ExcelType.Excel03);
        }

        else
        {
            stream = NpoiExcelHelper.RenderToExcelIList(models, excelColumns, NpoiExcelHelper.ExcelType.Excel07);

        }

        StreamWriter sw = new StreamWriter(Server.MapPath(filepath));
        stream.CopyTo(sw.BaseStream);
        sw.Flush();
        sw.Close();

        Response.Redirect(filepath.Replace("~", ""));

    }

}
